package com.huixuebao.after.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huixuebao.after.dto.*;
import com.huixuebao.after.entity.*;
import com.huixuebao.after.mapper.*;
import com.huixuebao.after.service.UserService;
import com.huixuebao.after.util.PasswordChecker;
import com.huixuebao.common.bean.ApiResult;
import com.huixuebao.common.enumeration.ResultCodeEnum;
import com.huixuebao.common.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    TokenMapper tokenMapper;
    @Autowired
    RoleMapper roleMapper;

    @Autowired
    MechanismMapper mechanismMapper;
    /**
     * 添加用户信息
     * @param userDTO
     * @return
     */
    @Override
    public ApiResult addUser(UserDTO userDTO,HttpServletRequest request) {

        ApiResult apiResult = new ApiResult();
        String userCode = userDTO.getUserCode();
        String userName = userDTO.getUserName();
        String mobileNo = userDTO.getMobileNo();
        String email = userDTO.getEmail();
        String password = userDTO.getPassword();
        String mechanismId = userDTO.getMechanismId();
        String userType = userDTO.getUserType();
        List<String> roleIds = Arrays.asList(userDTO.getRoleIds().split(","));
        Integer userState = userDTO.getUserState();
        try {
            if (CollUtil.isEmpty(roleIds)) {
                apiResult.setMessage("请添加角色，不能为空!");
                return apiResult;
            }
            String userId = JWTUtils.getUserId(request);
            UserEntity userEntity = new UserEntity();
            //判断账号名称是否被占用
            int userCod = userMapper.selectCount(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUserCode, userCode));
            if (userCod > 0) {
                apiResult.setMessage("你的userCode已经注册!");
                apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                return apiResult;
            }
            if ("0".equals(userType)) {
                //新增用户
                if (userCode.isEmpty() && userName.isEmpty() && password.isEmpty() && mobileNo.isEmpty() && mechanismId.isEmpty() && userState != null) {
                    log.info("代*号为必填字段，请添加字段信息！！");
                    apiResult.setSuccess(false);
                    apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                    apiResult.setMessage("代*号为必填字段，请添加字段信息");
                } else {
                    String id = "100000000000000000000000001";
                        userEntity.setUserCode(userCode);
                        userEntity.setUserName(userName);
                        userEntity.setUserState(userState);
                        userEntity.setPassword(SecureUtil.md5(password));
                        userEntity.setMobileNo(mobileNo);
                        userEntity.setEmail(email);
                        userEntity.setCreateTime(new Date());
                        userEntity.setUserType(userType);
                        userEntity.setMechanismId(id);
                        userMapper.insert(userEntity);
                        String newUserId = userEntity.getId();

                        roleIds.forEach(roleId -> {
                            //为用户新增角色
                            UserRoleEntity userRoleEntity = new UserRoleEntity();
                            userRoleEntity.setUserId(newUserId);
                            userRoleEntity.setRoleId(roleId);
                            userRoleMapper.insert(userRoleEntity);
                        });
                        apiResult.setSuccess(true);
                        apiResult.setCode(ResultCodeEnum.SUCCESS.getCode());
                        apiResult.setMessage("新增用户成功!!!");
                    return apiResult;
                }
            }else {
                //新增用户
                if (userState != null && userName.isEmpty() && password.isEmpty() && mobileNo.isEmpty() && mechanismId.isEmpty() && userCode.isEmpty()) {
                    log.info("代*号为必填字段，请添加字段信息！！");
                    apiResult.setSuccess(false);
                    apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                    apiResult.setMessage("代*号为必填字段，请添加字段信息");
                } else {
                    //判断账号名称是否被占用
                    int count = userMapper.selectCount(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUserCode, userCode));
                    if (count > 0) {
                        apiResult.setMessage("你的userCode已经注册!");
                        apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                        return apiResult;
                    }
                    userEntity.setUserName(userName);
                    userEntity.setUserCode(userCode);
                    userEntity.setPassword(SecureUtil.md5(password));
                    userEntity.setMobileNo(mobileNo);
                    userEntity.setEmail(email);
                    userEntity.setCreateTime(new Date());
                    userEntity.setUserType(userType);
                    userEntity.setMechanismId(mechanismId);
                    userEntity.setUserState(userState);
                    userMapper.insert(userEntity);
                    String newUserId = userEntity.getId();
                    roleIds.forEach(roleId -> {
                        //为用户新增角色
                        UserRoleEntity userRoleEntity = new UserRoleEntity();
                        userRoleEntity.setRoleId(roleId);
                        userRoleEntity.setUserId(newUserId);
                        userRoleMapper.insert(userRoleEntity);
                    });
                    apiResult.setSuccess(true);
                    apiResult.setCode(ResultCodeEnum.SUCCESS.getCode());
                    apiResult.setMessage("新增用户成功!!!");
                    return apiResult;
                }
            }
        } catch (Exception e) {
            log.info("新增用户失败！！哦哦哦哦");
            apiResult.setSuccess(false);
            apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
            apiResult.setMessage("新增用户失败！！");
            return apiResult;
        }
        return apiResult;
    }

    /**
     * 编辑用户
     * @param userDTO
     * @return
     */
    @Override
    public ApiResult editUser(UserDTO userDTO, HttpServletRequest request) {
        //编辑用户
        String id = userDTO.getId();
        String userName = userDTO.getUserName();
        String email = userDTO.getEmail();
        String mobileNo = userDTO.getMobileNo();
        List<String> roleIds = Arrays.asList(userDTO.getRoleIds().split(","));
        String userType = userDTO.getUserType();
        Integer userState = userDTO.getUserState();
        String userClient = JWTUtils.getUserType(request);
        ApiResult apiResult = new ApiResult();
        if (CollectionUtils.isEmpty(roleIds)) {
            apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
            apiResult.setMessage("请添加用户角色,不能为空!");
            return apiResult;
        }
        try {
            UserEntity userEntity = new UserEntity();
            if (userClient.equals(0)) {
                int countId = userMapper.selectCount(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getId, id));
                if (countId > 0) {
                    userEntity.setId(id);
                    userEntity.setUserName(userName);
                    userEntity.setUserState(userState);
                    userEntity.setMobileNo(mobileNo);
                    userEntity.setEmail(email);
                    userEntity.setUpdateTime(new DateTime());
                    userEntity.setUserType(userType);
                    userMapper.updateById(userEntity);
                    userRoleMapper.delete(new LambdaQueryWrapper<UserRoleEntity>().eq(UserRoleEntity::getUserId, id));
                    roleIds.forEach(roleId -> {
                        log.info("更新角色id", userEntity.getId(), roleId);
                        //将用户角色改编辑
                        UserRoleEntity userRoleEntity = new UserRoleEntity();
                        userRoleEntity.setRoleId(roleId);
                        userRoleEntity.setUserId(userEntity.getId());
                        userRoleMapper.insert(userRoleEntity);
                    });
                    apiResult.setSuccess(true);
                    apiResult.setCode(ResultCodeEnum.SUCCESS.getCode());
                    apiResult.setMessage("编辑角色成功!!");
                }
            }else {
                int countId = userMapper.selectCount(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getId, id));
                if (countId > 0) {
                    userEntity.setId(id);
                    userEntity.setUserName(userName);
                    userEntity.setUserState(userState);
                    userEntity.setMobileNo(mobileNo);
                    userEntity.setEmail(email);
                    userEntity.setUpdateTime(new DateTime());
                    userEntity.setUserType(userType);
                    userMapper.updateById(userEntity);
                    userRoleMapper.delete(new LambdaQueryWrapper<UserRoleEntity>().eq(UserRoleEntity::getUserId, id));
                    roleIds.forEach(roleId -> {
                        log.info("更新角色id", userEntity.getId(), roleId);
                        //将用户角色改编辑
                        UserRoleEntity userRoleEntity = new UserRoleEntity();
                        userRoleEntity.setRoleId(roleId);
                        userRoleEntity.setUserId(userEntity.getId());
                        userRoleMapper.insert(userRoleEntity);
                    });
                    apiResult.setSuccess(true);
                    apiResult.setCode(ResultCodeEnum.SUCCESS.getCode());
                    apiResult.setMessage("编辑角色成功!!");
                }
            }
        } catch (Exception e) {
            log.error("后台管理系统编辑用户异常:", e);
            apiResult.setMessage(e.getMessage());
            apiResult.setSuccess(false);
            apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
            apiResult.setMessage("编辑角色失败!!");
        }
        return apiResult;
    }

    /**
     * 分页查询user信息
     * @param current
     * @param size
     * @param userName
     * @param userState
     * @return
     */
    @Override
    public ApiResult getUserList(Integer current, Integer size, String userName,String userCode,Integer userState,HttpServletRequest request) {
        ApiResult apiResult = new ApiResult();
        String userId = JWTUtils.getUserId(request);
        String userType = JWTUtils.getUserType(request);
        log.info(userId + "test!!!!!!!!!!!!");
        Map<String,Object> map = new HashMap<>();
        List<AfterUserDTO> dtoList = null;
        map.put("userName",userName);
        map.put("userState",userState);
        map.put("userCode",userCode);
        try{
            if (ObjectUtil.isNotNull(current) && ObjectUtil.isNotNull(size)) {
                if ("0".equals(userType)){
                    IPage<AfterUserDTO> page = new Page<>(current, size);
                    IPage<AfterUserDTO> result = userMapper.selectAfterUser(page,map);
                    apiResult.setData(result);
                    apiResult.setSuccess(true);
                    apiResult.setCode(ResultCodeEnum.SUCCESS.getCode());
                    apiResult.setMessage("管理端用户查询用户分页列表成功");
                }else {
                    IPage<AfterUserDTO> page = new Page<>(current, size);
                    UserEntity userEntity = userMapper.selectById(userId);
                    if(userEntity!=null && userEntity.getMechanismId()!=null){
                        MerchantsDTO md = new MerchantsDTO();
                        md.setId(userEntity.getMechanismId());
                        getChilds(md);
                        List<String> list= new ArrayList<>();
                        getIdList(md,list);
                        map.put("mids",list);
                        userMapper.selectAfterUser(page,map);
                        apiResult.setData(page);
                        apiResult.setSuccess(true);
                        apiResult.setCode(ResultCodeEnum.SUCCESS.getCode());
                        apiResult.setMessage("机构端用户查询用户信息成功！！");
                    }
                }
            } else {
                UserEntity userEntity = userMapper.selectById(userId);
                if(userEntity!=null && userEntity.getMechanismId()!=null){
                    MerchantsDTO md = new MerchantsDTO();
                    md.setId(userEntity.getMechanismId());
                    getChilds(md);
                    List<String> list= new ArrayList<>();
                    getIdList(md,list);
                    map.put("mids",list);
                    dtoList =userMapper.selectAfterUserList(map);
                }
                apiResult.setData(dtoList);
                apiResult.setSuccess(true);
                apiResult.setCode(ResultCodeEnum.SUCCESS.getCode());
                apiResult.setMessage("查询用户所以列表！！");
            }
        }catch (Exception e){
            log.info("获取用户信息列表异常!!!!");
            apiResult.setSuccess(false);
            apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
            apiResult.setMessage("获取用户列表信息失败!!");
        }
        return apiResult;
    }

    /**
     * 更新密码
     */
    @Override
    public ApiResult updatePassword(UserDTO userDTO){
        ApiResult apiResult = new ApiResult();
        try{
            String id = userDTO.getId();
            String password = userDTO.getPassword();
            UserEntity userId = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getId,id));
            if (StrUtil.isEmpty(id)) {
                apiResult.setSuccess(false);
                apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                apiResult.setMessage("当前用户为查询到，请联系管理员!!");
            }else {
                if (PasswordChecker.check(password)) {
                    userId.setPassword(SecureUtil.md5(password));
                    userId.setUpdateTime(new DateTime());
                    userMapper.updateById(userId);
                    apiResult.setSuccess(true);
                    apiResult.setCode(ResultCodeEnum.SUCCESS.getMessage());
                    apiResult.setMessage("修改密码成功!");
                }else {
                    apiResult.setSuccess(false);
                    apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                    apiResult.setMessage("密码规则是字母加数字!!");
                }
            }
        }catch (Exception e){
            log.info("更新密码失败");
            apiResult.setSuccess(false);
            apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
            apiResult.setMessage("更新密码失败");
        }
        return apiResult;
    }

    private List<MerchantsDTO> listDTO(String pid) {
        List<MechanismEntity> list = mechanismMapper.selectList(new LambdaQueryWrapper<MechanismEntity>().eq(MechanismEntity::getPid, pid));
        List<MerchantsDTO> result = new ArrayList<>();
        list.forEach(entity -> {
            MerchantsDTO dto = new MerchantsDTO();
            BeanUtil.copyProperties(entity, dto);
            result.add(dto);
        });
        return result;
    }

    private void getChilds(MerchantsDTO dto) {
        List<MerchantsDTO> childs = listDTO(dto.getId());
        dto.setChildren(childs);
        for (MerchantsDTO getChilds : childs) {
            getChilds(getChilds);
        }
    }

    private void getIdList(MerchantsDTO dto,List<String> ids){
        ids.add(dto.getId());
        dto.getChildren().forEach((merchantsDTO)->{
            getIdList(merchantsDTO,ids);
        });
    }
}
